package com.example.ymm.modules1.service.impl.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2UserGetuserinfoRequest;
import com.dingtalk.api.response.OapiV2UserGetuserinfoResponse;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.bo.YmUserDetails;
import com.example.ymm.dto.Constants;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.CommonResult;
import com.example.ymm.model.TableList;
import com.example.ymm.model.UserLogin;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.my.user.DbUser;
import com.example.ymm.modules1.mapper.my.user.DbUserMapper;
import com.example.ymm.modules1.service.dd.AccessTokenService2;
import com.example.ymm.modules1.service.dd.DdUserServer;
import com.example.ymm.modules1.service.dd.ms.AccessTokenH5Service2;
import com.example.ymm.modules1.service.dto.DbUserNoteQueryCriteria;
import com.example.ymm.modules1.service.dto.DbUserQueryCriteria;
import com.example.ymm.modules1.service.dto.ImportUserExcelDto;
import com.example.ymm.modules1.service.user.DbDeptUserService;
import com.example.ymm.modules1.service.user.DbUserNoteService;
import com.example.ymm.modules1.service.user.DbUserService;
import com.example.ymm.util.*;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@DSTransactional
@DS("master")
@Slf4j
public class DbUserServiceImpl extends BaseServiceImpl<DbUserMapper, DbUser> implements DbUserService, UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.expiration}")
    private Long expiration;




    @Autowired
    AccessTokenService2 accessTokenService2;

    @Autowired
    AccessTokenH5Service2 accessTokenH5Service2;

    @Autowired
    DdUserServer ddUserServer;
    @Autowired
    DbDeptUserService dbDeptUserService;

    @Autowired
    DbUserNoteService dbUserNoteService;

    @Override
    public TableList<DbUser> list(DbUserQueryCriteria criteria, YmPageDto ymPage) {
        IPage<DbUser> page = new Page<DbUser>(ymPage.getPage(),ymPage.getPageSize());
        baseMapper.selectPage(page,QueryHelpPlus.getPredicate(DbUser.class, criteria));
        TableList<DbUser> tableList=new TableList(page);
        return tableList;
    }


    @Override
    public TableList<DbUser> countList(DbUserQueryCriteria criteria, YmPageDto pageDto) {
        IPage<DbUser> page = new Page<DbUser>(pageDto.getPage(), pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(DbUser.class, criteria);
        predicate.orderByDesc("create_time");
        baseMapper.selectPage(page, predicate);
        TableList<DbUser> tableList = new TableList(page);
        tableList.getList().forEach(r->{
            DbUserNoteQueryCriteria noteQueryCriteria=new DbUserNoteQueryCriteria();
            noteQueryCriteria.setUserId(r.getUserId());
            BigDecimal userDurations = dbUserNoteService.getUserDurations(noteQueryCriteria);
            if(UtilValidate.isNotEmpty(userDurations)){
                BigDecimal divide = userDurations.divide(new BigDecimal(60), 2, BigDecimal.ROUND_HALF_UP);
                r.setReadTimes(divide.doubleValue());
            }

        });
        return tableList;
    }

    public List<DbUser> queryAll(DbUserQueryCriteria criteria) {
        List<DbUser> result =baseMapper.selectList(QueryHelpPlus.getPredicate(DbUser.class, criteria));
        return result;
    }

    public YmUserDetails loadByUsername(String username){
        //获取用户信息
        DbUser user = findByUserName(username);
        if (user != null) {

            YmUserDetails yhUserDetails = getUserDetailByDbUser(user);

            return yhUserDetails;
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    public YmUserDetails loadUserByUsername(String userId){
        //获取用户信息
        DbUser user = findByUserId(userId);
        if (user != null) {

            YmUserDetails yhUserDetails = getUserDetailByDbUser(user);

            return yhUserDetails;
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }


    public YmUserDetails getUserDetailByDbUser(DbUser dbUser){
        UserLogin userLogin=new UserLogin();
        userLogin.setDbUser(dbUser);
        userLogin.setId(dbUser.getUserId());
        userLogin.setPassword(null);
        userLogin.setUserName(dbUser.getUserName());
        YmUserDetails yhUserDetails = new YmUserDetails(userLogin);
        return  yhUserDetails;
    }

    @Override
    public DbUser findByUserId(String userId) {


        LambdaQueryWrapper<DbUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DbUser::getUserId,userId);
        List<DbUser> dbUsers = baseMapper.selectList(wrapper);
        DbUser dbUser=null;
        if(UtilValidate.isNotEmpty(dbUsers)){
            dbUser=dbUsers.get(0);
        }
        return dbUser;
    }

    @Override
    public DbUser addUser(JSONObject json) {
        String userid = json.getString("userid");
        DbUser user = findByUserId(userid);
        if(UtilValidate.isEmpty(user)){
            user=new DbUser();
            user.setState(Constants.STATUS_ACTIVE);
            user.setUserId(userid);
            user.setUserName(json.getString("name"));
            if(json.containsKey("unionid")){
                user.setUnionid(json.getString("unionid"));
            }
            if(json.containsKey("associated_unionid")){
                user.setAssociatedUnionid(json.getString("associated_unionid"));
            }
            if(json.containsKey("dept_id_list")){
                user.setDeptIdList(json.getString("dept_id_list"));
            }

            saveOrUpdate(user);
            if(json.containsKey("dept_id_list")){
                //调整部门
                JSONArray deptIdList=json.getJSONArray("dept_id_list");
                dbDeptUserService.joinDeptId(deptIdList.getString(0),user.getUserId());
            }
        }else{
            boolean isUp=false;
            DbUser n_u=new DbUser();
            n_u.setUserId(userid);
            if(UtilValidate.isEmpty(user.getLevelName())){
                n_u.setLevelName("C2");
                isUp=true;
            }
            if(json.containsKey("unionid")){
                n_u.setUnionid(json.getString("unionid"));
                isUp=true;
            }
            if(json.containsKey("associated_unionid")){
                isUp=true;
                n_u.setAssociatedUnionid(json.getString("associated_unionid"));
            }
            if(json.containsKey("dept_id_list")){
                isUp=true;
                n_u.setDeptIdList(json.getString("dept_id_list"));
            }
            if(isUp){
                updateById(n_u);
                if(json.containsKey("dept_id_list")){
                    //调整部门
                    JSONArray deptIdList=json.getJSONArray("dept_id_list");
                    dbDeptUserService.joinDeptId(deptIdList.getString(0),user.getUserId());
                }
            }

        }
        return user;
    }


    @Override
    public DbUser editUser(DbUser user) {

        saveOrUpdate(user);
        return user;
    }

    @Override
    public DbUser findByUserName(String userName) {
        LambdaQueryWrapper<DbUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DbUser::getUserName,userName);
        List<DbUser> dbUsers = baseMapper.selectList(wrapper);
        DbUser dbUser=null;
        if(UtilValidate.isNotEmpty(dbUsers)){
            dbUser=dbUsers.get(0);
        }
        return dbUser;
    }

    @Override
    public void importExcel(ImportUserExcelDto dto) {
        dto.getList().forEach(e->{
            String userName = e.getUserName();
            String levelName = e.getLevelName();
            if(UtilValidate.isNotEmpty(levelName)){
                DbUser user = findByUserName(userName);
                if(UtilValidate.isNotEmpty(user)){
                    user.setLevelName(levelName);
                    saveOrUpdate(user);
                }
            }


        });
    }

    @Override
    public CommonResult login(String code) {
        String token = null;
        //密码需要客户端加密后传递
        try {

            // 获取access_token，注意正式代码要有异常流处理
           // String access_token= accessTokenService.getAccessToken();
            String access_token= accessTokenService2.getAccessToken();
            // 获取用户信息

            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            log.info("---自动登录access_token:"+access_token);
            req.setCode(code);
            OapiV2UserGetuserinfoResponse rsp = null;

            String userId=null;

            JSONObject json=null,result=null;
//            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
//            OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
//            request.setCode(code);
//            request.setHttpMethod("GET");
//            OapiUserGetuserinfoResponse response;


            try {
                rsp = client.execute(req, access_token);
              //  response = client.execute(request, access_token);
                log.info("---dd:结果:"+rsp.getBody());
                log.info(rsp.getBody());
                if(UtilValidate.isNotEmpty(rsp.getBody())){
                    json=JSONObject.parseObject(rsp.getBody());
                    if("0".equals(json.getString("errcode"))){
                        result=json.getJSONObject("result");

                    }
                }
            //    userId =response.getUserid();

            } catch (ApiException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                throw new YmException(e.getMessage());
            }
            if(UtilValidate.isNotEmpty(result)){
                userId = result.getString("userid");
            }

            //log.info("--获取登录用户信息:"+result);

            if(UtilValidate.isEmpty(userId)){
                throw new YmException("自动登录失败，无法获取自动登录用户信息!");
            }
            // 查询得到当前用户的userId
            // 获得到userId之后应用应该处理应用自身的登录会话管理（session）,避免后续的业务交互（前端到应用服务端）每次都要重新获取用户身份，提升用户体验

           // JSONObject userInfo = ddUserServer.getUserInfoByUserId(userId);
            addUser(result);
            YmUserDetails userDetails = loadUserByUsername(userId);
            UserLogin userLogin = userDetails.getUserLogin();
            DbUser dbUser = userLogin.getDbUser();
            if(Constants.STATUS_DISABLED== dbUser.getState()){
                throw new BadCredentialsException("该账号已被冻结，请联系管理员.");
            }
            List<String> roleList=new ArrayList<>();
            roleList.add("ms_user");
            userLogin.setRoleList(roleList);
            token = jwtTokenUtil.generateToken(userDetails);
            // userDetails.setToken(token);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String s = JSONObject.toJSONString(userLogin);
            redisUtil.set(RedisKeyManager.user_token_key+userLogin.getId()+":"+token, s,expiration);
//            updateLoginTimeByUsername(username);
            Map<String,Object> map=new HashMap<>();
            map.put("token",tokenHead+token);
            map.put("userId",dbUser.getUserId());
            map.put("role",roleList);
            map.put("homePath","/dashboard/analysis2");
            map.put("permission",new ArrayList<>());
            map.put("phone",dbUser.getPhone());
            map.put("userName",dbUser.getUserName());
            // cacheMapService.setUserLogin(pdUserLogin.getUserId(),userDetails);
            return CommonResult.success(map,"登录成功!");
        } catch (AuthenticationException e) {
            log.error("h5登录异常:", e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Override
    public CommonResult login2(String code) {
        String token = null;
        //密码需要客户端加密后传递
        try {

            // 获取access_token，注意正式代码要有异常流处理
            String access_token= accessTokenService2.getAccessToken();
            // 获取用户信息

            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            log.info("---小程序自动  access_token:"+access_token);
            req.setCode(code);
            OapiV2UserGetuserinfoResponse rsp = null;

            String userId=null;

            JSONObject json=null,result=null;
//            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
//            OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
//            request.setCode(code);
//            request.setHttpMethod("GET");
//            OapiUserGetuserinfoResponse response;


            try {
                rsp = client.execute(req, access_token);
                //  response = client.execute(request, access_token);
                log.info("---小程序自动 登录:结果:"+rsp.getBody());
                log.info(rsp.getBody());
                if(UtilValidate.isNotEmpty(rsp.getBody())){
                    json=JSONObject.parseObject(rsp.getBody());
                    if("0".equals(json.getString("errcode"))){
                        result=json.getJSONObject("result");

                    }else{
                        EmailUtil.sendEmail("1055162826@qq.com","小程序自动 登录异常:"+json.getString("sub_msg"),json.getString("errmsg"));

                    }
                }
                //    userId =response.getUserid();

            } catch (ApiException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                throw new YmException(e.getMessage());
            }
            if(UtilValidate.isNotEmpty(result)){
                userId = result.getString("userid");
            }

            //log.info("--获取登录用户信息:"+result);

            if(UtilValidate.isEmpty(userId)){
                throw new YmException("自动登录失败，无法获取自动登录用户信息!");
            }
            // 查询得到当前用户的userId
            // 获得到userId之后应用应该处理应用自身的登录会话管理（session）,避免后续的业务交互（前端到应用服务端）每次都要重新获取用户身份，提升用户体验

            // JSONObject userInfo = ddUserServer.getUserInfoByUserId(userId);
            addUser(result);
            YmUserDetails userDetails = loadUserByUsername(userId);
            UserLogin userLogin = userDetails.getUserLogin();
            DbUser dbUser = userLogin.getDbUser();
            if(Constants.STATUS_DISABLED== dbUser.getState()){
                throw new BadCredentialsException("该账号已被冻结，请联系管理员.");
            }
            List<String> roleList=new ArrayList<>();
            roleList.add("ms_user");
            userLogin.setRoleList(roleList);
            token = jwtTokenUtil.generateToken(userDetails);
            // userDetails.setToken(token);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String s = JSONObject.toJSONString(userLogin);
            redisUtil.set(RedisKeyManager.user_token_key+userLogin.getId()+":"+token, s,expiration);
//            updateLoginTimeByUsername(username);
            Map<String,Object> map=new HashMap<>();
            map.put("token",tokenHead+token);
            map.put("userId",dbUser.getUserId());
            map.put("role",roleList);
            map.put("homePath","/dashboard/analysis2");
            map.put("permission",new ArrayList<>());
            map.put("phone",dbUser.getPhone());
            map.put("userName",dbUser.getUserName());
            // cacheMapService.setUserLogin(pdUserLogin.getUserId(),userDetails);
            return CommonResult.success(map,"登录成功!");
        } catch (AuthenticationException e) {
            log.error("h5登录异常:", e);
            return CommonResult.error(e.getMessage());
        }
    }

    /**
     * 和 login一摸一样的功能和逻辑，但是获取的access_token是不一样的因为是不同应用
     * 获得user_id 等用户信息 与小程序用户相同
     * @param code
     * @return
     */
    @Override
    public CommonResult loginH5(String code) {
        String token = null;
        //密码需要客户端加密后传递
        try {

            // 获取access_token，注意正式代码要有异常流处理
            String access_token= accessTokenH5Service2.getAccessToken();
            // 获取用户信息

            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
//            System.out.println("---授权码code"+code);
            req.setCode(code);
            OapiV2UserGetuserinfoResponse rsp = null;

            String userId=null;

            JSONObject json=null,result=null;

            try {
                rsp = client.execute(req, access_token);
                //  response = client.execute(request, access_token);
                log.info("---h5自动 登录:结果:"+rsp.getBody());
                if(UtilValidate.isNotEmpty(rsp.getBody())){
                    json=JSONObject.parseObject(rsp.getBody());
                    if("0".equals(json.getString("errcode"))){
                        result=json.getJSONObject("result");

                    }else{
                        EmailUtil.sendEmail("1055162826@qq.com","h5自动 登录异常:"+json.getString("sub_msg"),json.getString("errmsg"));

                    }
                }
                //    userId =response.getUserid();

            } catch (ApiException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
            if(UtilValidate.isNotEmpty(result)){
                userId = result.getString("userid");
            }

            log.info("--h5获取登录用户信息:"+result);

            if(UtilValidate.isEmpty(userId)){
                throw new YmException("自动登录失败，无法获取自动登录用户信息!");
            }
            // 查询得到当前用户的userId
            // 获得到userId之后应用应该处理应用自身的登录会话管理（session）,避免后续的业务交互（前端到应用服务端）每次都要重新获取用户身份，提升用户体验

            addUser(result);
            YmUserDetails userDetails = loadUserByUsername(userId);
            UserLogin userLogin = userDetails.getUserLogin();
            DbUser dbUser = userLogin.getDbUser();
            if(Constants.STATUS_DISABLED== dbUser.getState()){
                throw new BadCredentialsException("该账号已被冻结，请联系管理员.");
            }
            token = jwtTokenUtil.generateToken(userDetails);

            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);

            List<String> roleList=new ArrayList<>();
            roleList.add("ms_user");
            userLogin.setRoleList(roleList);
            String s = JSONObject.toJSONString(userLogin);
            redisUtil.set(RedisKeyManager.user_token_key+userLogin.getId()+":"+token, s,expiration);

            Map<String,Object> map=new HashMap<>();
            map.put("token",tokenHead+token);
            map.put("userId",dbUser.getUserId());
            map.put("roleList",roleList);
            map.put("homePath","/dashboard/analysis2");
            map.put("permission",new ArrayList<>());
            map.put("phone",dbUser.getPhone());
            map.put("userName",dbUser.getUserName());
            return CommonResult.success(map,"登录成功!");
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
            return CommonResult.error(e.getMessage());
        }
    }


    @Override
    public CommonResult loginByUserId(String userId) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            // 获取用户信息
            YmUserDetails userDetails = loadUserByUsername(userId);
            UserLogin userLogin = userDetails.getUserLogin();
            if(UtilValidate.isEmpty(userLogin)){
                throw new YmException("查无数据");
            }
            DbUser dbUser = userLogin.getDbUser();
            if(Constants.STATUS_DISABLED== dbUser.getState()){
                throw new BadCredentialsException("该账号已被冻结，请联系管理员.");
            }
            token = jwtTokenUtil.generateToken(userDetails);
            // userDetails.setToken(token);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            List<String> roleList=new ArrayList<>();
            roleList.add("ms_user");
            userLogin.setRoleList(roleList);
            String s = JSONObject.toJSONString(userLogin);
            redisUtil.set(RedisKeyManager.user_token_key+userLogin.getId()+":"+token, s,expiration);
//            updateLoginTimeByUsername(username);

            Map<String,Object> map=new HashMap<>();
            map.put("token",tokenHead+token);
            map.put("userId",dbUser.getUserId());
            map.put("roleList",roleList);
            map.put("homePath","/dashboard/analysis2");
            map.put("permission",new ArrayList<>());
            map.put("phone",dbUser.getPhone());
            map.put("userName",dbUser.getUserName());
            // cacheMapService.setUserLogin(pdUserLogin.getUserId(),userDetails);
            return CommonResult.success(map,"登录成功!");
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
            return CommonResult.error(e.getMessage());
        }
    }


    @Override
    public CommonResult loginByEx(String userName, HttpSession session) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            // 获取用户信息
            DbUser user = findByUserName(userName);
            YmUserDetails userDetails =null;
            String userId=null;
            if (UtilValidate.isNotEmpty(user)) {
                userId=user.getUserId();
                userDetails = getUserDetailByDbUser(user);
            }else{
                UserLogin userLogin=new UserLogin();
                userId="场外人员:"+userName;
                userLogin.setId("场外人员:"+userName);
                userLogin.setPassword(null);
                userLogin.setUserName(userName);
                userDetails = new YmUserDetails(userLogin);
            }
            UserLogin userLogin = userDetails.getUserLogin();
            if(UtilValidate.isEmpty(userLogin)){
                throw new YmException("查无数据");
            }

            token = jwtTokenUtil.generateToken(userDetails);
            // userDetails.setToken(token);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            List<String> roleList=new ArrayList<>();
            roleList.add("ms_user");
            userLogin.setRoleList(roleList);
            String s = JSONObject.toJSONString(userLogin);
            redisUtil.set(RedisKeyManager.user_token_key+userLogin.getId()+":"+token, s,expiration);
//            updateLoginTimeByUsername(username);
            session.setAttribute("userName", userName);
            Map<String,Object> map=new HashMap<>();
            map.put("token",tokenHead+token);
            map.put("userId",userId);
            map.put("roleList",roleList);
            map.put("homePath","/dashboard/analysis2");
            map.put("permission",new ArrayList<>());
//            map.put("phone",);
            map.put("userName",userName);
            // cacheMapService.setUserLogin(pdUserLogin.getUserId(),userDetails);
            return CommonResult.success(map,"登录成功!");
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
            return CommonResult.error(e.getMessage());
        }
    }

    @Override
    public void sycnDimissionUserList() {
        YmPageDto ymPageDto = new YmPageDto();
        Integer page=1;
        ymPageDto.setPage(page);
        ymPageDto.setPageSize(50);
        TableList<DbUser> list = list(null, ymPageDto);
        operatorDimissionUser(list.getList());
        long totalPage = list.getTotalPage();
        while (page<totalPage){
            page++;
            ymPageDto.setPage(page);
          //  System.out.println("--页码:"+page);
            TableList<DbUser> list2 = list(null, ymPageDto);
            operatorDimissionUser(list2.getList());
        }
    }

    public void operatorDimissionUser(List<DbUser> users){
        List<String> userIds=new ArrayList<>();
        for(DbUser dbUser: users){
            userIds.add(dbUser.getUserId());
        }
        if(UtilValidate.isNotEmpty(userIds)){
            List<String> dimissionUserList = ddUserServer.getDimissionUserList(userIds);
            log.info("--离职人员:"+dimissionUserList);
            if(UtilValidate.isNotEmpty(dimissionUserList)){
                removeByIds(dimissionUserList);
            }
        }

    }



}
